//
//  WSMineViewController.m
//  GroupFourFM
//
//  Created by dllo on 15/12/22.
//  Copyright © 2015年 GroupFour. All rights reserved.
//

#import "WSMineViewController.h"
#import "WHAboutViewController.h"
#import "WHHeaderView.h"
#import "WSHistoryViewController.h"
#import "WSLoginViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "WSConcernViewController.h"

@interface WSMineViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,WHHeaderViewDelegate, WSLoginViewControllerDelegate>

@property( nonatomic, strong) WSBaseTableView *mineTableView;
@property( nonatomic, strong) UIImageView *backgroundImageView;
@property( nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) WHHeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *recordArr;
@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, copy) NSString *str;


@end

@implementation WSMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createTableView];
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = YES;
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
        _str = @"注销";
    } else {
        _str = @"登陆";
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = NO;
}

#pragma mark - 创建tableView
-(void)createTableView
{
    
    
    self.mineTableView = [[WSBaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEIGHT_TABLE) style:UITableViewStylePlain];
    self.mineTableView.backgroundColor = [UIColor whiteColor];
    //self.mineTableView.contentInset = UIEdgeInsetsMake(SCREEN_WIDTH*0.62 , 0, 0, 0);
    [self.view addSubview:self.mineTableView];
    self.mineTableView.sectionFooterHeight = 10.f;
#pragma mark - 加约束

    [self.mineTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
        
    }];
    
    self.headerView = [[WHHeaderView alloc] initWithFrame:CGRectMake(0, 0, 375*WID, 160*HEI)];
    self.mineTableView.tableHeaderView = self.headerView;
    self.headerView.loginDelegate = self;
    
    self.mineTableView.dataSource = self;
    self.mineTableView.delegate = self;
    [self.mineTableView registerClass:[WSBaseTableViewCell class] forCellReuseIdentifier:@"mineTableCell"];
    self.mineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 数组初始化
    self.recordArr = [NSMutableArray array];
    
    [self changeUserName];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0){
        
        return 2;
    }

    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WSBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mineTableCell"];
    
    if (indexPath.section == 0) {
        //夜间模式按钮
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0){
            
            cell.textLabel.text = @"我的关注";
            cell.imageView.image = [UIImage imageNamed:@"me_setting_liked"];
            
        }else{
            
            cell.textLabel.text = @"播放历史";
            cell.imageView.image = [UIImage imageNamed:@"me_my_device"];
        }
    }
    
    else if (indexPath.section == 1 )
    {
        cell.textLabel.text = @"清除缓存";
        cell.imageView.image = [UIImage imageNamed:@"cell_delete_h"];
    }
    else if (indexPath.section == 2)
    {
        cell.textLabel.text = @"关于我们";
        cell.imageView.image = [UIImage imageNamed:@"setting_sm_icon"];
    }
    else {
    
        cell.textLabel.text = _str;
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 1){
            
            WSHistoryViewController *history = [[WSHistoryViewController alloc] init];
            [self.navigationController pushViewController:history animated:YES];
            
        }else{
            
            WSConcernViewController *concern = [[WSConcernViewController alloc] init];
            
            [self.navigationController pushViewController:concern animated:YES];
        }
        
    }
    else if (indexPath.section == 1) {
        NSUInteger size = [[SDImageCache sharedImageCache] getSize];
        float cacheSize = size / 1024.0 / 1024.0;
        NSString *string = [NSString stringWithFormat:@"缓存大小为%.2fMB", cacheSize];
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleActionSheet];
        
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
        
        // 创建提示框按钮
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"清除缓存" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            // 清除缓存
            [[SDImageCache sharedImageCache] clearDisk];
            // hud单例
            self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self.hud.labelText = @"清除缓存成功";
            self.hud.mode = MBProgressHUDModeText;
            [self.hud hide:YES afterDelay:1];
            
        }];
        // 创建提示框按钮
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        // 将按钮放在提示框上
        [alertC addAction:action];
        [alertC addAction:action1];
    }
    else if (indexPath.section == 2)
    {
        WHAboutViewController *aboutVC = [[WHAboutViewController alloc] init];
        [(WSTabBarController *)self.tabBarController isHiddenTabBar:YES withViewController:aboutVC];
        [self.navigationController pushViewController:aboutVC animated:YES];
        
    }
    else {
    
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"uId"];
            [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"isLogin"];
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"注销?" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                self.headerView.name = @"登陆";
                _str = @"登陆";
                [self.mineTableView reloadData];
            }];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertC addAction:cancel];
            [alertC addAction:action];
            [self presentViewController:alertC animated:YES completion:nil];
        } else {
            [self presentToLoginC];
        }
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375*WID, 10)];
    footer.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.91 alpha:1];
    return footer;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375*WID, 60)];
    header.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.91 alpha:1];
    UIButton *recordingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    recordingBtn.layer.cornerRadius = 5;
    [header addSubview:recordingBtn];
#pragma mark - 录音按钮 
    // 点击开始录音
    [recordingBtn addTarget:self action:@selector(recordAction:) forControlEvents:UIControlEventTouchDown];
    [recordingBtn setTitle:@"开始录音" forState:UIControlStateNormal];
    [recordingBtn setTitle:@"松开结束" forState:UIControlStateHighlighted];
    [recordingBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    // 松开按钮录音结束
    [recordingBtn addTarget:self action:@selector(endRecordAction:) forControlEvents:UIControlEventTouchUpInside];
    recordingBtn.backgroundColor = [UIColor redColor];
    [recordingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    
        make.left.mas_equalTo(@80);
        make.right.mas_equalTo(@-80);
        make.top.mas_equalTo(@15);
        make.bottom.mas_equalTo(@-15);
        
    }];
    
    return header;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0){
        
        return 70.f;
    }else{
        
        return 0;
    }
}
#pragma mark - scrollView协议方法

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.headerView updateHeaderView:scrollView.contentOffset];
}

#pragma mark - 录音
-(void)recordAction:(UIButton *)btn{
    
    NSLog(@"录音");
    
    //1.创建录音器
    
    //1.1URL 是录音文件保存的地址
    //音频文件保存在沙盒 document/20150228171912.caf
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *timeStr = [dateFormatter stringFromDate:[NSDate date]];
    
    //音频文件名
    NSString *audioName = [timeStr stringByAppendingString:@".caf"];
    
    //doc目录
    
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    //拼接音频URL
    NSString *fileURL = [doc stringByAppendingPathComponent:audioName];
    NSLog(@"%@",fileURL);
    
    //保存文件路径到数组
    [self.recordArr addObject:fileURL];
    
    //setting 录音时的设置
    NSMutableDictionary *settings = [NSMutableDictionary dictionary];
    //音频编码格式
    settings[AVFormatIDKey] = @(kAudioFormatAppleIMA4); //音频采样频率
    settings[AVSampleRateKey] = @(8000.0);
    //音频频道
    settings[AVNumberOfChannelsKey] = @(1);
    //音频线性音频的位深度
    settings[AVLinearPCMBitDepthKey] = @(8);
    
    self.recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:fileURL] settings:settings error:nil];
    
    //录音的准备
    [self.recorder prepareToRecord];
    
    //录音
    [self.recorder record];
    
    
    
    
}

- (void)endRecordAction:(UIButton *)btn
{
    NSLog(@"结束录音");
    //录音的时间
    double duration = self.recorder.currentTime;
    NSLog(@"录音的时间%lf",self.recorder.currentTime);
    
    
    NSLog(@"%s",__func__);
    [self.recorder stop];
    
    //判断录音的时间否大于0.5
    if(duration <=0.5){
        //移除最后的录音文件
        
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        self.hud.color = [UIColor blackColor];
        
        self.hud.labelText = @"录音时间太短";
        
        self.hud.dimBackground = NO;
        
        self.hud.labelFont = [UIFont systemFontOfSize:17];
        
        self.hud.mode = MBProgressHUDModeCustomView;
        
        self.hud.backgroundColor = [UIColor clearColor];
        
        [self.hud hide:YES afterDelay:2.8];
        
        [self.recordArr removeLastObject];
    }
}

#pragma mark - 登录

-(void)presentToLoginC{
    
    WSLoginViewController *loginVC = [[WSLoginViewController alloc] init];
    loginVC.delegate = self;
    UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loginVC];
    navC.navigationBarHidden = YES;
    [self presentViewController:navC animated:YES completion:nil];
}

- (void)changeUserName {

    NSString *name = nil;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"]) {
        name = [[NSUserDefaults standardUserDefaults] objectForKey:@"uId"];
        _str = @"注销";
    }
    else {
    
        name = @"登陆";
        _str = @"登陆";
    }
    self.headerView.name = name;
    [self.mineTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
